<template>
  <div class="menu-display">
    <!-- Business Header Section -->
    <div class="business-header" v-if="business">
      <div class="business-info-container">
        <img :src="business.head" alt="Business Logo" class="business-logo">
        <div class="business-details">
          <h2 class="business-name">{{ business.businessName }}</h2>
          <div class="business-rating-container">
            <el-rate
                v-model="business.rating"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
                :max="5"
                class="rating-stars"
            />
            <span class="rating-text">{{ business.rating.toFixed(1) }}</span>
          </div>
          <p class="business-address">
            <el-icon><Location /></el-icon>
            {{ business.address }}
          </p>
        </div>
      </div>
    </div>

    <!-- Food Menu Section -->
    <div class="food-menu" v-if="foods.length > 0">
      <h3 class="section-title">菜单</h3>
      <div class="food-list">
        <el-card
            v-for="food in foods"
            :key="food.foodId"
            class="food-card"
            shadow="hover"
        >
          <div class="food-content">
            <img :src="food.sample || 'https://via.placeholder.com/100?text=Food+Image'"
                 alt="Food Image"
                 class="food-image">
            <div class="food-info" style="margin-left: 30px">
              <h4 class="food-name">{{ food.foodName }}</h4>
              <p class="food-desc" v-if="food.description">{{ food.description }}</p>
              <p class="food-price">¥{{ food.price.toFixed(2) }}</p>
              <div class="food-actions">
                <el-button
                    @click="decreaseQuantity(food.foodId)"
                    :disabled="getCartQuantity(food.foodId) <= 0"
                    size="large"
                    circle
                    class="action-btn"
                >
                  <el-icon color="#909399"><RemoveFilled /></el-icon>
                </el-button>
                <span class="quantity">{{ getCartQuantity(food.foodId) }}</span>
                <el-button
                    @click="increaseQuantity(food.foodId)"
                    size="large"
                    circle
                    class="action-btn"
                >
                  <el-icon color="#409EFF"><CirclePlusFilled /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    <div v-else class="empty-foods">
      <el-empty description="暂无菜品" />
    </div>

    <!-- Fixed Shopping Cart Section -->
    <div class="fixed-cart-container" v-if="cartTotal > 0">
      <div class="fixed-cart">
        <div class="cart-info">
          <div class="cart-total-items">
            <el-badge :value="cartTotalItems" class="badge">
              <el-icon :size="24"><ShoppingCart /></el-icon>
            </el-badge>
          </div>
          <div class="cart-price-info">
            <span class="total-label">总计:</span>
            <span class="total-price">¥{{ cartTotal.toFixed(2) }}</span>
          </div>
        </div>
        <el-button
            type="primary"
            class="checkout-btn"
            @click="checkout"
            :loading="isCheckingOut"
        >
          去结算
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue'
import {Location, ShoppingCart, CirclePlusFilled, RemoveFilled} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'

const business = ref(null)
const foods = ref([])
const cart = ref({}) // {foodId: quantity}
const isCheckingOut = ref(false)

// Fetch business details based on ID from localStorage
const fetchBusinessDetails = async () => {
  try {
    const businessId = localStorage.getItem('business_id')
    if (!businessId) {
      console.error('No business ID found')
      return
    }

    const token = localStorage.getItem('access_token')
    if (!token) {
      console.error('No access token found')
      return
    }

    const response = await fetch(`http://localhost:8080/business/id/${businessId}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    // Ensure rating is a number
    data.rating = Number(data.rating) || 0
    business.value = data
  } catch (error) {
    console.error('Error fetching business details:', error)
  }
}

// Fetch food list for the business
const fetchFoodList = async () => {
  try {
    const businessId = localStorage.getItem('business_id')
    if (!businessId) {
      console.error('No business ID found')
      return
    }

    const token = localStorage.getItem('access_token')
    if (!token) {
      console.error('No access token found')
      return
    }

    const response = await fetch(`http://localhost:8080/food/business/${businessId}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    foods.value = await response.json()
  } catch (error) {
    console.error('Error fetching food list:', error)
  }
}

// Cart functionality
const increaseQuantity = (foodId) => {
  if (!localStorage.getItem('access_token')) {
    window.location.href = '/login'
    return
  }

  if (!cart.value[foodId]) {
    cart.value[foodId] = 0
  }
  cart.value[foodId]++
}

const decreaseQuantity = (foodId) => {
  if (!localStorage.getItem('access_token')) {
    window.location.href = '/login'
    return
  }

  if (cart.value[foodId] && cart.value[foodId] > 0) {
    cart.value[foodId]--
    if (cart.value[foodId] === 0) {
      delete cart.value[foodId]
    }
  }
}

const getCartQuantity = (foodId) => {
  return cart.value[foodId] || 0
}

// Checkout function
// Checkout function
const checkout = () => {
  if (!localStorage.getItem('access_token')) {
    window.location.href = '/login'
    return
  }

  // Prepare order data
  const orderData = {
    business: business.value,
    orderItems: Object.entries(cart.value)
        .filter(([_, quantity]) => quantity > 0)
        .map(([foodId, quantity]) => {
          const food = foods.value.find(f => f.foodId === parseInt(foodId))
          return {
            foodId: parseInt(foodId),
            quantity,
            foodName: food?.foodName || '未知菜品',
            foodPrice: food?.price || 0,
            foodImage: food?.sample || 'https://via.placeholder.com/100?text=Food+Image'
          }
        }),
    wechatId: localStorage.getItem('wechat_id') || '',
    totalAmount: cartTotal.value
  }

  // Store order data in localStorage
  localStorage.setItem('pendingOrder', JSON.stringify(orderData))

  // Redirect to confirmation page
  window.location.href = '/order/confirm'
}

// Computed properties
const cartItems = computed(() => {
  return Object.entries(cart.value)
      .filter(([_, quantity]) => quantity > 0)
      .map(([foodId, quantity]) => ({
        foodId: parseInt(foodId),
        quantity
      }))
})

const cartTotal = computed(() => {
  return cartItems.value.reduce((total, item) => {
    const food = foods.value.find(f => f.foodId === item.foodId)
    return total + (food ? food.price * item.quantity : 0)
  }, 0)
})

const cartTotalItems = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

onMounted(() => {
  fetchBusinessDetails()
  fetchFoodList()
})
</script>

<style scoped>
.menu-display {
  max-width: 800px;
  margin: 0 auto;
  padding: 12px;
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 80px; /* Space for fixed cart */
}

.business-header {
  background-color: white;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.business-info-container {
  display: flex;
  align-items: center;
  gap: 15px;
}

.business-logo {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.business-details {
  flex: 1;
}

.business-name {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.business-rating-container {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  gap: 8px;
}

.rating-stars :deep(.el-rate__icon) {
  font-size: 16px;
  margin-right: 2px;
}

.rating-text {
  font-size: 14px;
  color: #ff9900;
  font-weight: bold;
}

.business-address {
  margin: 0;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 5px;
}

.business-address .el-icon {
  font-size: 16px;
  color: #999;
}

/* Food menu styles */
.food-menu {
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 20px;
}

.food-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 15px;
}

.food-card {
  border-radius: 8px;
}

.food-content {
  display: flex;
  padding: 10px;
  gap: 15px;
}

.food-image {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  object-fit: cover;
}

.food-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.food-name {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: bold;
}

.food-desc {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.food-price {
  margin: 0;
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.food-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
}

.action-btn {
  padding: 6px;
  width: 28px;
  height: 28px;
}

.quantity {
  min-width: 20px;
  text-align: center;
  font-size: 14px;
}

.section-title {
  font-size: 16px;
  color: #333;
  margin: 0 0 15px 0;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: "";
  display: inline-block;
  width: 3px;
  height: 14px;
  background: #409eff;
  border-radius: 2px;
  margin-right: 8px;
}

.empty-foods {
  background-color: white;
  border-radius: 12px;
  padding: 40px 0;
  text-align: center;
}

/* Fixed shopping cart styles */
.fixed-cart-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  padding: 10px;
  z-index: 1000;
}

.fixed-cart {
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
}

.cart-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.cart-total-items {
  position: relative;
}

.badge :deep(.el-badge__content) {
  top: 5px;
  right: 5px;
}

.cart-price-info {
  display: flex;
  align-items: center;
  gap: 5px;
}

.total-label {
  font-size: 16px;
  font-weight: bold;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.checkout-btn {
  width: 120px;
  height: 40px;
}

@media (max-width: 480px) {
  .business-logo {
    width: 70px;
    height: 70px;
  }

  .business-name {
    font-size: 16px;
  }

  .business-address {
    font-size: 13px;
  }

  .rating-stars :deep(.el-rate__icon) {
    font-size: 14px;
  }

  .rating-text {
    font-size: 13px;
  }

  .food-content {
    flex-wrap: wrap;
  }

  .food-image {
    width: 80px;
    height: 80px;
  }

  .checkout-btn {
    width: 100px;
  }
}

@media (min-width: 600px) {
  .business-logo {
    width: 90px;
    height: 90px;
  }

  .business-name {
    font-size: 20px;
  }

  .business-address {
    font-size: 15px;
  }

  .rating-stars :deep(.el-rate__icon) {
    font-size: 18px;
  }

  .rating-text {
    font-size: 16px;
  }

  .food-image {
    width: 120px;
    height: 120px;
  }
}
</style>